package com.script

import com.CustomScript
import com.FileCrcMode
import com.utils.PropertiesUtils
import com.utils.ScriptUtils.appConfig
import com.utils.ScriptUtils.contrastFile
import com.utils.ScriptUtils.script
import org.apache.logging.log4j.kotlin.logger

private val propertiesUtils = PropertiesUtils.instance

script.customScript.add(object : CustomScript {

    override fun onAfterSubpackageStart() {
        super.onAfterSubpackageStart()
        fixFileNameCrc()
    }

})

private fun fixFileNameCrc() {

    val fileCrc = appConfig.fileCrc
    val crcMode = fileCrc.mode
    logger.info("执行最后的上传前工作处理 fileCrcMode=$crcMode")
    if (crcMode == FileCrcMode.NONE) return

    // 执行打包layadcc
    val addOssPush = contrastFile.addOssPush
    val deleteOssPush = contrastFile.deleteOssPush
    val fileOss = addOssPush + deleteOssPush
    logger.info("总数 ${fileOss.size}")
    if (fileOss.isNotEmpty()) {
        val replaceNameFile = appConfig.replaceNameFile
        val mapSet = propertiesUtils.keySet().associate {
            var pathKey = contrastFile.getRelativePath(it)
            if (pathKey != null) {
                for ((key, value) in replaceNameFile) {
                    if (pathKey!!.endsWith(key)) {
                        pathKey = pathKey.replace(key, value)
                    }
                }
            }
            pathKey to propertiesUtils.get(it)
        }
        val keeps = fileCrc.keepFileName
        val include = fileCrc.include

        val filter = fileOss.filter { file ->
            // 首先检查是否在保留列表中，如果在保留列表中则不需要CRC处理
            val isKept = keeps.any {
                contrastFile.validatePath(file, it)
            }
            if (isKept) {
                false
            } else {
                include.isEmpty() || include.any {
                    contrastFile.validatePath(file, it)
                }
            }
        }
        for (packPath in filter) {
            val pack = contrastFile.getRelativePath(packPath)
            var crc = mapSet[pack]
            if (crc == null) {
                crc = packPath.crc()
                logger.debug("path=${packPath} create=$crc")
            } else {
                logger.debug("path=${packPath} cache=$crc")
            }
            packPath.renameWithCrc32(crc, crcMode)
            logger.debug("修改文件名字：${packPath} -> ${packPath.absolutePathString}")
        }
    }

}